package com.oly.cms.general.service.search;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import com.oly.cms.common.domain.entity.CmsLink;
import com.oly.cms.common.enums.CommonVisibleEnums;

import com.oly.cms.general.service.IGeneralSearchService;
import com.oly.cms.query.mapper.LinkSearchMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class GeneralLinkServiceImpl implements IGeneralSearchService {

    @Autowired
    private LinkSearchMapper linkSearchMapper;

    public List<CmsLink> listCmsLinks(CmsLink cmsLink) {
        cmsLink.setVisible(CommonVisibleEnums.SHOW.ordinal());
        return linkSearchMapper.listCmsLinks(cmsLink);
    }

    public CmsLink selectCmsLinkById(long linkId) {
        CmsLink cmsLink = linkSearchMapper.selectCmsLinkById(linkId);
        cmsLink = (cmsLink == null || cmsLink.getVisible() != CommonVisibleEnums.SHOW.ordinal()) ? null : cmsLink;
        return linkSearchMapper.selectCmsLinkById(linkId);
    }

    public List<CmsLink> linkTree(Long parentId, List<CmsLink> treeList) {
        List<CmsLink> list = new ArrayList<>();
        Optional.ofNullable(treeList).orElse(new ArrayList<>())
                .stream()
                // 第一次筛选出主父节点列表进入循环，循环里面 进入递归 筛选出递归传递的从父节点列表
                .filter(root -> root.getParentId().equals(parentId))
                // 递归，最末的父节点从整个列表筛选出它的子节点列表依次组装
                .forEach(tree -> {
                    List<CmsLink> children = linkTree(tree.getLinkId(), treeList);
                    tree.setChildren(children);
                    list.add(tree);
                });
        return list;
    }

}
